package com.jt.www.remote;

import com.jt.www.util.ConfigUtils;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.util.Arrays;

@Component
@Configuration
public class FilesRestTemplateClient {

    @Resource
    ConfigUtils configUtils;

    @Bean(name = "innerSvcRestTemplate")
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate(
                Arrays.asList(new HttpMessageConverter[]{new StringHttpMessageConverter(Charset.forName("UTF-8")), new ByteArrayHttpMessageConverter()}));
    }

    @HystrixCommand(fallbackMethod = "idgFallback", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000"),
            @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "4000"),})
    public ResponseEntity<byte[]> requestId(Long id) {
        HttpHeaders headers = new HttpHeaders();
        RestTemplate restTemplate = this.restTemplate();

        ResponseEntity<byte[]> resp = restTemplate.exchange(
                configUtils.getFileUrl() + id,
                HttpMethod.GET,
                new HttpEntity<byte[]>(headers),
                byte[].class);
        return resp;
    }

    public String idgFallback() {
        throw new RuntimeException("call idg-svc failed");
    }

}
